< previous page page_411 next page >

Page 411
0411-01.gif
Figure 12.25
Objects may intersect more than
one quadtree node.
You must be careful to avoid drawing objects that lie in more than one quadtree node multiple times. Modify the drawing object classes so that they contain a Boolean variable Drawn to indicate whether the object has already been drawn. In the objects' Draw subroutines, check this value. If the object has already been drawn, do not draw it again.
A Quadtree Implementation
The code that follows shows a Visual Basic implementation of the QtreeNode class representing quadtree nodes. Its xmin, xmax, ymin, and ymax variables store the bounds of the drawing area represented by the node. The NWchild, NEchild, SWchild, and SEchild variables are references to the node's children. The Objects collection holds the drawing objects contained in the node if the node is a leaf node.
The Add subroutine adds a new object to the node. First it determines whether the node has been divided into subnodes. If so, it calls subroutine PlaceObject to place the new object in the correct subnodes. Otherwise, the Add routine inserts the new object in the node's Objects collection. Then, if the collection contains too many objects, the routine calls subroutine Divide to split the node into subnodes and divide the objects among the children.
Subroutine PlaceObject compares the object's bounds with the bounds of the quadtree node's children. It then invokes the Add subroutine for any children that intersect the new object's bounds.
Subroutine Divide first creates four new QtreeNode objects, one for each quadtree child node. It then examines the objects in the Objects collection and uses PlaceObject to put each in the correct child nodes. Finally, it sets the Objects collection to Nothing because this node is no longer a child node.
The SetDrawn method sets the Drawn flag for all the objects contained in a node. The main program uses this routine to reset the objects' Drawn flags after drawing them.
The Draw subroutine takes as parameters the coordinate bounds of the area to draw. If that area does not intersect the area represented by the node, the routine does nothing. Otherwise, if the node is a leaf node, it makes each of the objects it contains draw itself. Finally, if the node is not a leaf node, it calls its children's Draw methods so they can draw the objects they contain.

 
< previous page page_411 next page >